/**
 * Notes: 充值套餐包服务 - 宠物门店预约小程序
 * Date: 2025-01-27
 */

const BaseService = require('./base_service.js');
const RechargePackageModel = require('../model/recharge_package_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class RechargePackageService extends BaseService {

	/**
	 * 获取充值套餐包列表
	 * @returns {Array} 套餐包列表
	 */
	async getPackageList() {
		let where = { status: RechargePackageModel.STATUS.ONLINE };
		let fields = '_id,name,amount,bonus,totalAmount,isRecommended,label,description';
		let orderBy = { amount: 1 }; // 按金额升序排列

		const result = await RechargePackageModel.getList(where, fields, orderBy, 1, 100, false, 0);
		
		// 转换数据格式，将分转换为元
		const packages = result.list.map(pkg => ({
			id: pkg._id,
			name: pkg.name,
			amount: pkg.amount / 100, // 转换为元
			bonus: pkg.bonus / 100,   // 转换为元
			totalAmount: pkg.totalAmount / 100, // 转换为元
			isRecommended: pkg.isRecommended,
			label: pkg.label || '',
			description: pkg.description || ''
		}));
		
		return packages;
	}

	/**
	 * 根据ID获取套餐包详情
	 * @param {string} packageId 套餐包ID
	 * @returns {Object} 套餐包详情
	 */
	async getPackageDetail(packageId) {
		let where = { _id: packageId, status: RechargePackageModel.STATUS.ONLINE };
		let fields = '_id,name,amount,bonus,totalAmount,isRecommended,label,description';

		const result = await RechargePackageModel.getOne(where, fields);
		
		if (!result) {
			throw new Error('套餐包不存在或已下架');
		}
		
		// 转换数据格式
		return {
			id: result._id,
			name: result.name,
			amount: result.amount / 100, // 转换为元
			bonus: result.bonus / 100,   // 转换为元
			totalAmount: result.totalAmount / 100, // 转换为元
			isRecommended: result.isRecommended,
			label: result.label || '',
			description: result.description || ''
		};
	}

	/**
	 * 管理员获取充值套餐包列表（包含已下架）
	 * @returns {Array} 套餐包列表
	 */
	async getAdminPackageList() {
		let where = {}; // 不过滤状态，获取所有套餐包
		let fields = '_id,name,amount,bonus,totalAmount,isRecommended,label,description,status,createTime,updateTime';
		let orderBy = { createTime: -1 }; // 按创建时间倒序排列

		const result = await RechargePackageModel.getList(where, fields, orderBy, 1, 100, false, 0);
		
		// 转换数据格式，将分转换为元
		const packages = result.list.map(pkg => ({
			_id: pkg._id,
			name: pkg.name,
			amount: pkg.amount / 100, // 转换为元
			bonus: pkg.bonus / 100,   // 转换为元
			totalAmount: pkg.totalAmount / 100, // 转换为元
			isRecommended: pkg.isRecommended,
			label: pkg.label || '',
			description: pkg.description || '',
			status: pkg.status,
			createTime: pkg.createTime,
			updateTime: pkg.updateTime
		}));
		
		return {
			code: 0,
			data: {
				list: packages,
				total: result.total
			},
			message: 'Success'
		};
	}

	/**
	 * 添加充值套餐包
	 * @param {Object} data 套餐包数据
	 * @returns {Object} 添加结果
	 */
	async addPackage(data) {
		// 检查套餐包名称是否重复
		const existPackage = await RechargePackageModel.getOne({ name: data.name });
		if (existPackage) {
			throw new Error('套餐包名称已存在');
		}

		// 构建套餐包数据
		const packageData = {
			_pid: 'A00',
			name: data.name,
			amount: data.amount * 100, // 转换为分
			bonus: (data.bonus || 0) * 100, // 转换为分
			totalAmount: (data.amount + (data.bonus || 0)) * 100, // 转换为分
			isRecommended: data.isRecommended || false,
			label: data.label || '',
			description: data.description || '',
			status: RechargePackageModel.STATUS.ONLINE,
			createTime: timeUtil.time(),
			updateTime: timeUtil.time()
		};

		const result = await RechargePackageModel.insert(packageData);
		
		return {
			code: 0,
			data: {
				packageId: result.id,
				message: '套餐包添加成功'
			},
			message: 'Success'
		};
	}

	/**
	 * 编辑充值套餐包
	 * @param {string} packageId 套餐包ID
	 * @param {Object} data 更新数据
	 * @returns {Object} 编辑结果
	 */
	async editPackage(packageId, data) {
		// 检查套餐包是否存在
		const existPackage = await RechargePackageModel.getOne({ _id: packageId });
		if (!existPackage) {
			throw new Error('套餐包不存在');
		}

		// 检查套餐包名称是否重复（排除自己）
		const duplicatePackage = await RechargePackageModel.getOne({ 
			name: data.name, 
			_id: { $ne: packageId } 
		});
		if (duplicatePackage) {
			throw new Error('套餐包名称已存在');
		}

		// 构建更新数据
		const updateData = {
			name: data.name,
			amount: data.amount * 100, // 转换为分
			bonus: (data.bonus || 0) * 100, // 转换为分
			totalAmount: (data.amount + (data.bonus || 0)) * 100, // 转换为分
			isRecommended: data.isRecommended || false,
			label: data.label || '',
			description: data.description || '',
			updateTime: timeUtil.time()
		};

		await RechargePackageModel.edit({ _id: packageId }, updateData);
		
		return {
			code: 0,
			data: {
				message: '套餐包编辑成功'
			},
			message: 'Success'
		};
	}

	/**
	 * 切换套餐包状态（启用/禁用）
	 * @param {string} packageId 套餐包ID
	 * @param {number} status 状态
	 * @returns {Object} 切换结果
	 */
	async togglePackageStatus(packageId, status) {
		// 检查套餐包是否存在
		const existPackage = await RechargePackageModel.getOne({ _id: packageId });
		if (!existPackage) {
			throw new Error('套餐包不存在');
		}

		// 更新状态
		const updateData = {
			status: status,
			updateTime: timeUtil.time()
		};

		await RechargePackageModel.edit({ _id: packageId }, updateData);
		
		return {
			code: 0,
			data: {
				message: status === RechargePackageModel.STATUS.ONLINE ? '套餐包已启用' : '套餐包已禁用'
			},
			message: 'Success'
		};
	}

	/**
	 * 删除充值套餐包
	 * @param {string} packageId 套餐包ID
	 * @returns {Object} 删除结果
	 */
	async deletePackage(packageId) {
		// 检查套餐包是否存在
		const existPackage = await RechargePackageModel.getOne({ _id: packageId });
		if (!existPackage) {
			throw new Error('套餐包不存在');
		}

		// 检查是否有相关的充值订单
		const RechargeModel = require('../model/recharge_model.js');
		const relatedOrders = await RechargeModel.getOne({ packageId: packageId });
		if (relatedOrders) {
			throw new Error('该套餐包已有相关订单，无法删除');
		}

		// 删除套餐包
		await RechargePackageModel.del({ _id: packageId });
		
		return {
			code: 0,
			data: {
				message: '套餐包删除成功'
			},
			message: 'Success'
		};
	}
}

module.exports = RechargePackageService;